package org.wisdom.ac.apis.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Optional;

import javax.imageio.ImageIO;

import org.wisdom.ac.apis.AuthController;
import org.wisdom.ac.application.service.AuthService;
import org.wisdom.ac.domain.resource.entity.AcCaptcha;
import org.wisdom.ac.domain.resource.repository.CaptchaRepository;
import org.wisdom.ac.domain.resource.repository.ResourceRepository;
import org.wisdom.ac.domain.role.repository.RoleRepository;
import org.wisdom.ac.domain.user.repository.UserRepository;
import org.wisdom.ac.dto.CaptchaDto;
import org.wisdom.ac.dto.LoginForm;
import org.wisdom.ac.dto.LoginInfo;
import org.wisdom.annotation.WisdomController;
import org.wisdom.context.WisdomContextHolder;
import org.wisdom.exception.BusinessException;
import org.wisdom.vo.ResponseResult;
import org.wisdom.vo.errorcode.impl.ErrorCode;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import cn.hutool.core.codec.Base64;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 鉴权API
 *
 * @author 张智研
 * @date 2022/05/27 12:03
 **/
@Slf4j
@RequiredArgsConstructor
@WisdomController
public class AuthControllerImpl implements AuthController {

    private final AuthService authService;
    private final DefaultKaptcha defaultKaptcha;
    private final CaptchaRepository captchaRepository;
    private final ResourceRepository resourceRepository;
    private final RoleRepository roleRepository;
    private final UserRepository userRepository;
    @Override
    public ResponseResult<LoginInfo> login(LoginForm loginForm) {
        log.info("用户登陆{}", loginForm);
        Optional<AcCaptcha> captchaOptional = this.captchaRepository.findById(loginForm.getUuid());
        if (captchaOptional.isPresent()) {
            if (!captchaOptional.get().getText().equals(loginForm.getCode())) {
                throw new BusinessException(1, "验证码错误!");
            }
        } else {
            throw new BusinessException(1, "验证码错误!");
        }
        LoginInfo loginInfo = this.authService.getToken(loginForm.getUsername(), loginForm.getPassword());
        return ResponseResult.ok(loginInfo);
    }

    @Override
    public ResponseResult<String> logout() {
        return ResponseResult.ok();
    }


    @Override
    public ResponseResult<String> updateToken(LoginForm loginForm) {
        log.info("token更新{}", loginForm);
        try {
            String token = this.authService.updateToken(loginForm.getToken());
            return ResponseResult.ok(token);
        } catch (RuntimeException e) {
            log.error("token更新失败", e);
            throw new BusinessException("token更新失败!");
        }
    }

    @Override
    public ResponseResult<CaptchaDto> captcha() {
        // 生成验证码
        AcCaptcha captcha = this.authService.generateCaptcha();
        // 根据文本内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(captcha.getText());
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", os);
            byte[] bytes = os.toByteArray();
            CaptchaDto captchaDto = new CaptchaDto();
            captchaDto.setUuid(captcha.getId());
            captchaDto.setCaptchaImage(Base64.encode(bytes));
            return ResponseResult.ok(captchaDto);
        } catch (IOException e) {
            throw new BusinessException(-10, e.getMessage());
        }
    }

    @Override
    public ResponseResult<String> hasPermission(String permission) {
        // 获取当前登录用户
        String userId = WisdomContextHolder.getContext().getUserId();
        if(userId == null) {
            return ResponseResult.fail(ErrorCode.LOGIN_ERROR);
        }
        boolean result = this.resourceRepository.hasPermission(userId,permission);
        if(result) {
            return ResponseResult.ok("拥有权限！");
        }else {
            return ResponseResult.fail("无此权限！");
        }
    }
}
